<?php	
class Obj_Image {
	
	protected static $t;
	protected static $initPath = '';
	
	public static function init() {
		self::$t = new Obj_DBTable_Image();
		self::$initPath = APPLICATION_PATH.'/../public/objects';
		if (!file_exists(self::$initPath)) {
			@mkdir(self::$initPath, 0777, true);
			if (!file_exists(self::$initPath)) {
				$translator = Zend_Registry::get('Zend_Translate');
				throw new Zend_Exception($translator->_('Нет прав доступа для создания папки! [Obj_Image]'));
			}
		}
		require_once APPLICATION_PATH.'/../library/PHPThumb/ThumbLib.inc.php';
	}
	
	public static function getImages($id, $main_only = false) {
		$ar_ = self::$t->getImages($id, $main_only);
		$ar = array();
		foreach ($ar_ as $k => $v) {
			$ar[$v['ID']] = $v;
		}
		return $ar;
	}
	
	public static function saveImage($arData, $id) {
		if ($id == 0) {
			return self::$t->insert($arData);
		}
		else self::$t->update($arData, 'ID = '.intval($id));
		return intval($id);
	}
	
	public static function getImage($id) {
		return self::$t->getImage((int) $id);
	}
	
	public static function deleteImage($id) {
		$image = self::getImage($id);
		if ($image === false) return;
		@unlink(self::getBasePath($id).'/'.$image['SourceName']);
		self::$t->delete('ID = '.intval($id));
	}

    public static function getImageExtension($name){
    	$_ = explode(".", (string)$name);
		if(sizeof($_)<1){
			return false;
		} else {
			return (string)$_[sizeOf($_)-1];
		}
    }
    
    public static function getBasePath($objectID) {
    	$s = trim($objectID);
    	$i = 3 - strlen($s);
    	$ss = self::$initPath.'/'.str_repeat('0', $i > 0 ? $i : 0).trim($s).'/'.trim($s);
    	if (!file_exists($ss)) {
    		@mkdir($ss, 0777, true);
    		if (!file_exists($ss)) {
				$translator = Zend_Registry::get('Zend_Translate');
				throw new Zend_Exception($translator->_('Нет прав доступа для создания папки! [Obj_Image]'));
    		}
    	}
    	return $ss;
    }
    
    public static function getBaseURL($objectID) {
    	$s = trim($objectID);
    	$i = 3 - strlen($s);
    	return HTTP_HOST.'/objects/'.str_repeat('0', $i > 0 ? $i : 0).trim($s).'/'.trim($s);
    }
    
    public static function uploadPhoto($file) {
    	//$file is array (name, tmp_name, size, type, object, main)
    	//let's make path to save
    	$path = self::getBasePath($file['object']);
    	$pi = pathinfo($file['name']);
    	$ext = '';
    	if (isset($pi['extension'])) $ext = '.'.$pi['extension'];
    	$filename = md5(microtime(true)).$ext;
    	move_uploaded_file($file['tmp_name'], $path.'/'.$filename); //TODO catch errors
    	//watermark
    	$watermark = APPLICATION_PATH.'/../library/PHPThumb/watermark1.png';
		$thumb = PhpThumbFactory::create($path.'/'.$filename);
		$dimensions = $thumb->getCurrentDimensions();
		$thumb->adaptiveResize($dimensions['width'], $dimensions['height']);
		$thumb->createWatermark($watermark, 'cc', 0);
		$thumb->save($path.'/'.$filename);    	
    	$userid = 0;
    	if (Zend_Auth::getInstance()->hasIdentity()) {
	    	$user = Zend_Auth::getInstance()->getIdentity();
    		$userid = $user->ID;
    	}
    	$image = array(	
    		'ID'			=> 0,
			'Type' 			=> CONTENT_TYPE_OBJECT,
			'ParentID' 		=> (int) $file['object'],
			'date' 			=> new Zend_Db_Expr('NOW()'),
			'author' 		=> (int)$userid,
			'ObjectType' 	=> OBJECT_TYPE_OBJECT_PHOTO,
			'Title' 		=> '',
			'Description' 	=> '',
			'seoTitle' 		=> '',
			'seoKeywords' 	=> '',
			'seoDescription'=> '',
			'OriginalName' 	=> $file['name'],
			'SourceName' 	=> $filename,
			'Size' 			=> $file['size'],
			'MimeType' 		=> $file['type'],
			'Active' 		=> 1,
			'Main' 			=> (int) $file['main']
		);    
		return $image;
    }
    
    public static function thumbnail($image, $iWidth = 0, $iHeight = 0) {
    	$translator = Zend_Registry::get('Zend_Translate');
    	if (intval($image) !== 0 && !is_array($image)) $image = self::$t->getImage((int) $image);
    	if (is_array($image)) {
    		if (!isset($image['ParentID']) || intval($image['ParentID']) === 0 || !isset($image['SourceName']) || trim($image['SourceName']) === '') {
    			throw new Zend_Exception($translator->_('Не верные данные рисунка [Obj_Image]'));
    		}
    	}
    	else {
    		throw new Zend_Exception($translator->_('Рисунок не существует [Obj_Image]'));
    	}
    	
    	$path = self::getBasePath($image['ParentID']);
    	if (!file_exists($path.'/'.$image['SourceName'])) {
    		return '';
    		throw new Zend_Exception($translator->_('Файла не существует! [Obj_Image]'));
    	}
    	if (file_exists($path.'/'.$iWidth.'x'.$iHeight.'_'.$image['SourceName'])) return self::getBaseURL($image['ParentID']).'/'.$iWidth.'x'.$iHeight.'_'.$image['SourceName'];
    	if ($iWidth === 0 && $iHeight === 0) return self::getBaseURL($image['ParentID']).'/'.$image['SourceName'];
		$_im = PhpThumbFactory::create($path.'/'.$image['SourceName']);
		$_im->setOptions(array('resizeUp' => true));
		if ($iWidth != 0 && $iHeight != 0) $_im->adaptiveResize($iWidth, $iHeight);
		else $_im->resize($iWidth, $iHeight);
		$_im->save($path.'/'.$iWidth.'x'.$iHeight.'_'.$image['SourceName']);
		return self::getBaseURL($image['ParentID']).'/'.$iWidth.'x'.$iHeight.'_'.$image['SourceName'];
    }
	
} Obj_Image::init();

